<template >
    <dg-card class="add-box">
        <template slot="header">
            <div class="card-header">
                <div>{{ title }}</div>
                <div>
                    <el-button v-permission="['XXXX_SUBMIT']" type="primary" @click="() => $emit('add')">上报</el-button>
                    <el-button @click="onCloseAdd">关闭</el-button>
                </div>
            </div>
        </template>
        <div>
            <div class="add-table-box">
                <div class="add-form">
                    <!-- <basic-info /> -->
                    <slot name="form"></slot>
                </div>
                <div class="list-info">
                    <div class="personnel-list">
                        <div class="title-operater">
                            <h2>案事件人员信息列表</h2>
                            <div class="operater">
                                <el-button type="primary" @click="addPeople">新增人员</el-button>
                                <el-upload
                                    class="upload"
                                    action=""
                                    :on-change="handleChange"
                                    :show-file-list="false"
                                    :file-list="fileListUpload"
                                    :limit="1"
                                    accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                                    :auto-upload="false"
                                >
                                    <el-button type="primary">批量导入</el-button>
                                </el-upload>
                                <!-- <el-upload action="" :before-upload="beforeUpload">
                                <el-button size="small" type="primary">批量导入</el-button>
                            </el-upload> -->
                                <el-button type="primary">下载模板</el-button>
                                <el-button type="primary" @click="onPersonInfo">获取人员信息</el-button>
                            </div>
                        </div>
                        <el-divider />

                        <el-table :data="data" style="width: 100%">
                            <el-table-column label="序号" type="index" width="70" fixed="left" />
                            <el-table-column label="操作" width="100" fixed="left">
                                <template slot-scope="{ $index }">
                                    <el-button @click="deleteRow($index)" type="text" size="small">删除</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column prop="xm" label="姓名" width="130">
                                <template slot-scope="{ row }">
                                    <el-input v-model="row.xm" :maxLength="10" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="sfzh" label="身份证号" width="240">
                                <template slot-scope="{ row, $index }">
                                    <div class="valid-box">
                                        <div class="el-icon-warning" v-if="data[$index].idError"></div>
                                        <el-input v-model="row.sfzh" :maxLength="18" @blur="onCheck(row)" />
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="xb" label="性别" width="100">
                                <template slot-scope="{ row }">
                                    <dg-select
                                        v-model="row.xb"
                                        :data="[
                                            { label: '男', value: '1' },
                                            { label: '女', value: '2' }
                                        ]"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column prop="hjd" label="户籍地" width="220">
                                <template slot-scope="{ row }">
                                    <el-input v-model="row.hjd" :maxLength="50" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="xzd" label="现住地" width="220">
                                <template slot-scope="{ row }">
                                    <el-input v-model="row.xzd" :maxLength="50" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="_ryys" label="人员要素" width="380">
                                <template slot-scope="{ row }">
                                    <div>
                                        <div v-for="(item, _i) in row._ryys" :key="_i" class="input-select">
                                            <el-input v-model="item.ysnr" :maxLength="50">
                                                <el-select v-model="item.yslx" slot="prepend" placeholder="请选择要素">
                                                    <el-option
                                                        :label="yaosu.label"
                                                        :value="yaosu.value"
                                                        v-for="yaosu in yaosuSelect"
                                                        :key="yaosu.value"
                                                    />
                                                </el-select>
                                            </el-input>
                                            <div class="btngroup">
                                                <el-button class="sub" @click="onAddYaosu(row)">
                                                    <i class="el-icon-plus"></i>
                                                </el-button>
                                                <el-button
                                                    class="sub"
                                                    :disabled="row._ryys.length === 1"
                                                    @click="onDeleteYaosu(row, _i)"
                                                >
                                                    <i class="el-icon-minus"></i>
                                                </el-button>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="wklx" label="稳控类型" width="180">
                                <template slot-scope="{ row }">
                                    <dg-select v-model="row.wklx" clearable :data="constant.wklx" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="wkdw" label="稳控单位" width="180">
                                <template slot-scope="{ row }">
                                    <dg-select
                                        v-model="row.wkdw"
                                        clearable
                                        :data="constant.lwdw"
                                        value-name="code"
                                        label-name="name"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column prop="gzqk" label="工作情况" width="300">
                                <template slot-scope="{ row }">
                                    <el-input v-model="row.gzqk" :maxLength="200" />
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <div class="relate-list">
                        <div class="title-operater">
                            <h2>关联信息</h2>
                            <el-button v-permission="['XXXX_GLXX']" type="primary" @click="openInfoModal">关联信息</el-button>
                        </div>
                        <el-divider />
                        <comm-table
                            ref="tableInfo"
                            :columns="infoColumns"
                            url="https://www.fastmock.site/mock/d45b9e67f495e3b24d522b72efc251ec/easy-mock/table/data"
                        >
                            <template slot-scope="{ row }">
                                <el-button type="text" @click="cancelRelated(row)">取消关联</el-button>
                            </template>
                        </comm-table>
                    </div>

                    <div class="relate-list">
                        <div class="title-operater">
                            <h2>所属专题</h2>
                            <el-button type="primary" v-permission="['XXXX_GLZT']" @click="openSpecialModal">关联专题</el-button>
                        </div>
                        <el-divider />
                        <comm-table
                            ref="tableInfo"
                            :columns="specialColumns"
                            url="https://www.fastmock.site/mock/d45b9e67f495e3b24d522b72efc251ec/easy-mock/table/data"
                        >
                            <template slot-scope="{ row }">
                                <el-button type="text" @click="cancelRelated(row)">取消关联</el-button>
                            </template>
                        </comm-table>
                    </div>
                </div>
            </div>
        </div>
    </dg-card>
</template>
   

<script>
import { mapState } from "vuex";
import { factorTypes, getPersonInfo } from "@/api/common";
import { CheckIDCard } from "@/components/FeatureExtr/data-process";
export default {
    name: "AddExterCommun",
    props: {
        // 主流程id
        id: {
            type: String
        },
        title: {
            type: String
        },
        peopleList: {
            type: Array,
            default: () => []
        }
    },

    data() {
        return {
            yaosuSelect: [],
            // 案事件人员列表数据
            data: [],
            // 上传的文件列表
            fileListUpload: [],
            // 关联信息表格头
            infoColumns: [
                { label: "序号", type: "index", width: 70 },
                { label: "操作", type: "operate" },
                { label: "上报时间", prop: "time" },
                { label: "信息编号", prop: "yyxtmc", width: 200 },
                { label: "标题", prop: "title" },
                { label: "上报单位", prop: "danwei" }
            ],
            // 关联专题表格头
            specialColumns: [
                { label: "序号", type: "index", width: 70 },
                { label: "操作", type: "operate" },
                { label: "创建时间", prop: "time" },
                //{ label: "专题编号", prop: "yyxtmc" },
                { label: "标题", prop: "title" },
                { label: "创建单位", prop: "danwei" }
            ]
        };
    },
    mounted() {
        factorTypes().then(({ data }) => {
            console.log(this.constant.only_ys);
            this.constant.only_ys.forEach((item) => {
                const _i = data.findIndex((child) => child.value === item);
                if (_i > -1) {
                    data.splice(_i, 1);
                }
            });
            this.yaosuSelect = data;
        });
    },
    computed: {
        ...mapState(["constant"])
    },
    watch: {
        peopleList: {
            deep: true,
            immediate: true,
            handler(val) {
                console.log(val, "我是要加进来的值");
                // 转换数据格式
                const getysnrs = (arr) => {
                    const _ryys = [];
                    arr.forEach((child) => {
                        child.ysnr.forEach((ysnr) => {
                            _ryys.push({ yslx: child.yslx, ysnr });
                        });
                    });
                    return _ryys;
                };
                this.data.forEach((item) => {
                    const _i = val.findIndex((child) => child.sfz[0] === item.sfzh);
                    if (item.sfzh && _i > -1) {
                        console.log(val);
                        const _ryys = getysnrs(val[_i].ysList);
                        // 过滤已经存在的相同要素
                        _ryys.forEach((ele) => {
                            if (!this.onIsExitYaosu(item._ryys, ele)) item._ryys.push(ele);
                        });
                        item.xm = val[_i].xm[0];
                        val.splice(_i, 1);
                    }
                });
                val.forEach((item) => {
                    this.data.push({
                        flowId: this.id,
                        xm: item.xm[0],
                        xb: "",
                        sfzh: item.sfz[0],
                        hjd: "",
                        xzd: "",
                        _ryys: getysnrs(item.ysList),
                        wklx: "",
                        wkdw: "",
                        gzqk: ""
                    });
                });
            }
        }
    },
    methods: {
        /**
         * 删除人员
         */
        deleteRow(_i) {
            this.$confirm("此操作将删除数据, 是否继续?").then(() => {
                this.data.splice(_i, 1);
            });
        },
        /**
         * 添加人员
         */
        addPeople() {
            this.data.push({
                flowId: this.id,
                xm: "",
                xb: "",
                sfzh: "",
                hjd: "",
                xzd: "",
                _ryys: [{ yslx: "", ysnr: "" }],
                wklx: "",
                wkdw: "",
                gzqk: ""
            });
        },
        /**
         * 打开关联信息弹窗
         */
        openInfoModal() {
            this.$dgLayer({
                title: "关联信息",
                component: require("./InfoModal"),
                area: ["60%", "960px"]
            });
        },
        /**
         * 打开关联专题弹窗
         */
        openSpecialModal() {
            this.$dgLayer({
                title: "关联专题",
                component: require("./SpecialModal"),
                area: ["60%", "960px"]
            });
        },
        /**
         * 取消关联心里
         */
        cancelRelated(row) {
            this.$confirm("此操作将删除数据, 是否继续?").then(() => {
                this.$refs.tableInfo.searchForm();
            });
        },
        /**
         * 提交前验证身份信息
         * isDraft为草稿时不做验证
         */
        onValidIdcard(isDraft) {
            return new Promise((resolve, reject) => {
                for (let i = 0; i < this.data.length; i++) {
                    if (isDraft === "0") {
                        if (!CheckIDCard(this.data[i].sfzh)) {
                            this.$set(this.data[i], "idError", true);
                            this.$message.warning("请检查身份证信息");
                            reject(false);
                        } else {
                            this.data[i].ryys = JSON.stringify(this.data[i]._ryys);
                        }
                    } else {
                        this.data[i].ryys = JSON.stringify(this.data[i]._ryys);
                    }
                }
                resolve(this.data);
            });
        },
        /**
         * 身份证验证
         */
        onCheck(item) {
            if (CheckIDCard(item.sfzh)) {
                this.$set(item, "idError", false);
            }
        },
        /**
         * 文件上传
         */
        handleChange(file, fileList) {
            this.fileTemp = file.raw;
            let fileName = file.raw.name;
            let fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            // 判断上传文件格式
            if (this.fileTemp) {
                if (fileType == "xlsx" || fileType == "xls") {
                    //  上传
                } else {
                    this.$message({
                        type: "warning",
                        message: "附件格式错误，请删除后重新上传！"
                    });
                }
            } else {
                this.$message({
                    type: "warning",
                    message: "请上传附件！"
                });
            }
        },
        /**
         * 添加要素
         */
        onAddYaosu(row) {
            row._ryys.push({ yslx: "", ysnr: "" });
        },
        /**
         * 删除要素
         */
        onDeleteYaosu(row, i) {
            console.log(row, i);
            row._ryys.splice(i, 1);
        },
        /**
         * 要素信息是否已存在
         */
        onIsExitYaosu(item, newYaosu) {
            const sameSelect = item.find((item) => item.yslx === newYaosu.yslx);
            if (!sameSelect) return false;
            return sameSelect.ysnr === newYaosu.ysnr;
        },
        /**
         * 获取人员要素信息
         */
        onPersonInfo() {
            const sfzhs = this.data.map((item) => item.sfzh);
            const loadingInstance = this.$loading({
                lock: true,
                text: "获取中...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
            });
            getPersonInfo({ sfzhs: sfzhs.join() }).then(({ data }) => {
                console.log(data, 111);
                data.forEach((item) => {
                    const person = this.data.find((child) => child.sfzh === item.sfzh);
                    if (person) {
                        Object.keys(person).forEach((child) => {
                            if (["_ryys", "ryys"].includes(child)) {
                                console.log(445466);
                            } else if (!person[child]) {
                                console.log(112, person[child]);
                                person[child] = item[child];
                            }
                        });
                    }
                });
                loadingInstance.close();
            });
        },
        /**
         * 关闭新增页面
         */
        onCloseAdd() {
            this.$confirm("是否保存为草稿?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "关闭",
                type: "warning"
            })
                .then(() => {
                    this.$emit("add", 1);
                })
                .catch(() => {
                    console.log(456);
                    this.$emit("onDeleteProcess");
                });
        }
    }
};
</script>
<style scoped lang='scss'>
.add-box {
    .card-header {
        display: flex;
        justify-content: space-between;
    }
}
.add-table-box {
    background: #fff;
    /deep/.el-divider--horizontal {
        margin: 10px 0;
    }
    .operater {
        display: flex;
        .upload {
            margin: 0 6px;
        }
    }
    .list-info > div {
        margin-top: 20px;
    }
    .title-operater {
        display: flex;
        justify-content: space-between;
    }
    /deep/.valid-box {
        display: flex;
        align-items: center;
        .el-icon-warning {
            color: #f56c6c;
            margin-right: 10px;
            font-size: 16px;
        }
    }
    .input-select {
        display: flex;
        margin-bottom: 12px;
        .btngroup {
            display: flex;
            width: 30%;
            margin-left: 8px;
            .sub {
                width: 32px;
                height: 32px;
                min-width: 32px;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        }
        .el-select {
            /deep/.el-input {
                width: 110px;
                input {
                    padding-right: 12px;
                }
            }
        }
        &:last-child {
            margin-bottom: 0;
        }
    }
}
</style>

